import { GForm, GFormSchema } from 'geminis-react';
import { useEffect, useRef, useState } from 'react';
// @ts-ignore
import { v4 as uuid } from 'uuid';

export default (props: any) => {
  const form = useRef<any>();
  const [id] = useState(props.location.query.businessKey || uuid());

  const onSchemaLoaded = (schema: GFormSchema) => {
    schema.data!.url = schema.data?.url?.replace('{id}', id);
  };

  useEffect(() => {
    if (props.location.query.defaultValue) {
      form.current
        ?.getForm()
        .setInitialValues(JSON.parse(props.location.query.defaultValue));
    }

    if (window.parent) {
      window.addEventListener('message', (event: MessageEvent<any>) => {
        const data = event.data;
        switch (data.cmd) {
          case 'submit':
            form.current
              ?.submit()
              .then(() => {
                let values = { ...form.current?.getForm().values };
                values = JSON.parse(JSON.stringify(values));
                window.parent.postMessage(
                  {
                    cmd: 'submitted',
                    params: {
                      data: values,
                      businessKey: id,
                    },
                  },
                  '*',
                );
              })
              .catch((err: any) => {
                window.parent.postMessage(
                  {
                    cmd: 'error',
                    params: {
                      error: err.message,
                    },
                  },
                  '*',
                );
              });
            break;
        }
      });

      window.setInterval(() => {
        window.parent.postMessage(
          {
            cmd: 'heightChanged',
            params: {
              height: document.documentElement.scrollHeight,
            },
          },
          '*',
        );
      }, 200);
    }
  }, []);

  return (
    <GForm
      ref={form}
      schema={{
        data: {
          methodLoad: 'get',
          autoload: props.location.query.autoload,
        },
      }}
      schemaPath={'/api/everydata/forms/' + props.location.query.id}
      onSchemaLoaded={onSchemaLoaded}
      onSubmitted={() => {}}
    />
  );
};
